package com.example.webdemo.interceptor;

import com.example.webdemo.controller.TokenController;
import com.example.webdemo.service.AuthenticationService;
import com.example.webdemo.util.JsonResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    // 添加 Log4j2 日志记录器
    private static final Logger logger = LogManager.getLogger(AuthenticationService.class);

    private final TokenController tokenController;

    // 改用构造器注入（推荐）
    @Autowired
    public LoginInterceptor(TokenController tokenController) {
        this.tokenController = tokenController;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 放行OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 检查登录状态
        logger.info("开始检查Token");
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("token") != null) {
            JsonResult<Object> result = tokenController.CheckToken(session.getAttribute("token"), session.getAttribute("username"));
            logger.info("Token合法");
            if(result.isSuccess()){
                logger.info("Token正确");
                return true;
            }
            logger.info("Token不对劲" + result.getMsg());
            response.getWriter().write("{\"code\":" + result.getCode() + ", \"msg\":" + result.getMsg());
        }

        // AJAX请求返回JSON错误
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401, \"msg\":\"会话过期，请重新登录\"}");
            return false;
        }

        // 普通请求重定向到登录页
        response.sendRedirect("/login");
        return false;
    }
}